package com.example.aicloud.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.aicloud.entity.Discuss;
import com.example.aicloud.entity.DiscussSupport;
import com.example.aicloud.entity.User;
import com.example.aicloud.entity.vo.CommentVO;
import com.example.aicloud.entity.vo.DiscussVO;
import com.example.aicloud.service.ICommentService;
import com.example.aicloud.service.IDiscussService;
import com.example.aicloud.service.IDiscussSupportService;
import com.example.aicloud.service.IUserService;
import com.example.aicloud.util.AppVariable;
import com.example.aicloud.util.ResponseEntity;
import com.example.aicloud.util.SecurityUtil;
import jakarta.annotation.Resource;
import org.simpleframework.xml.core.Validate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Wrapper;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import static com.example.aicloud.util.AppVariable.PAGE_SIZE;

@RestController
@RequestMapping("/discuss")
public class DiscussController {
    /**
     * 添加话题讨论
     */
    @Resource
    private IDiscussService discussService;
    @Resource
    private ThreadPoolTaskExecutor threadPool;
    @Resource
    private IUserService userService;
    @Resource
    private ICommentService commentService;
    @Resource
    private KafkaTemplate kafkaTemplate;
    @Resource
    private IDiscussSupportService discussSupportService;
    @PostMapping("/add")
    public ResponseEntity add(@Validate Discuss discuss) {
        discuss.setUid(SecurityUtil.getCurrentUser().getUid());
        boolean save = discussService.save(discuss);
        if (save){
            return  ResponseEntity.success("添加成功");
        }
        return ResponseEntity.fail("添加失败");
    }

    /**
     * 获取我的话题列表
     */
    @PostMapping("/mylist")
    public ResponseEntity getMylist() {
        Long uid = SecurityUtil.getCurrentUser().getUid();
        return ResponseEntity.success(discussService.list(
                Wrappers.lambdaQuery(Discuss.class)
                        .eq(Discuss::getUid, uid)
                        .orderByDesc(Discuss::getDid)
        ));
    }

    /**
     * 获取列表(分页)
     * @param  page 当前第几页
     * @param  type:1: 推荐（点赞数排序）  2： 最细时间排序
     */
    @PostMapping("/list")
    public ResponseEntity list(Integer page, Integer type) {
        // 参数预处理
        if (type == null || type <= 0){
            type = 1;
        }
        if (page==null || page <= 0){
            page =1;
        }
        QueryWrapper<Discuss> queryWrapper = new QueryWrapper<>();
        if (type == 1){ //根据点赞数进行排序
            queryWrapper.orderByDesc("supportcount");
        }else { // 根据创建时间排序
            queryWrapper.orderByDesc("did"); //did跟createtime的顺序一样，但did是主键，聚簇索引查询效率高
        }
        Page<Discuss> result = discussService.page(new Page<>(page, PAGE_SIZE),
                queryWrapper
        );
        return ResponseEntity.success(result);
    }

    /**
     * 话题删除
     */
    @PostMapping("/delete")
    public ResponseEntity delete(Long did) {
        if (did == null || did < 0){
            return ResponseEntity.fail("参数错误！");
        }
        boolean remove = discussService.remove(
                Wrappers.lambdaQuery(Discuss.class)
                        .eq(Discuss::getDid, did)
                        .eq(Discuss::getUid,SecurityUtil.getCurrentUser().getUid())
        );
        if (remove){
            return ResponseEntity.success("删除成功");
        }
        return ResponseEntity.fail("删除失败");
    }

    /**
     * 查询讨论详情
     */
    @PostMapping("/detail")
    public ResponseEntity detail(Long did) throws ExecutionException, InterruptedException {
        if (did == null || did <= 0){
            return ResponseEntity.fail("参数错误！");
        }
        Discuss discuss = discussService.getById(did);
        if (discuss!=null && discuss.getDid() > 0){
            // 添加阅读量 +1
            threadPool.submit(() -> {
                //1. 更新数据库
                discussService.updateReadCount(did);
                //2. 返回对象阅读数+1
                discuss.setReadcount(discuss.getReadcount()+1);
            });
            // 任务1： 查询 discuss 中的username
            CompletableFuture<DiscussVO> task1 = CompletableFuture.supplyAsync(() -> {
                // 对象转换
                DiscussVO discussVO = BeanUtil.toBean(discuss, DiscussVO.class);
                User user = userService.getById(discuss.getUid());
                if (user!=null && user.getUid() > 0){
                    discussVO.setUsername(user.getUsername());
                }
                return discussVO;
            },threadPool);

            // 任务2:  查询 discuss 对应的 comment
            CompletableFuture<List<CommentVO>> task2 = CompletableFuture.supplyAsync(() -> {
                return commentService.getCommentList(discuss.getDid());
            },threadPool);

            CompletableFuture.allOf(task1, task2); //等待task1和task2执行完成
            HashMap<String, Object> result = new HashMap<>();
            result.put("discuss",task1.get());
            result.put("commentlist",task2.get());
            return ResponseEntity.success(result);
        }{
            return ResponseEntity.fail("参数错误！");
        }

    }

    @PostMapping("/support")
    public ResponseEntity support(Long did) {
        if (did == null || did <= 0){
            return ResponseEntity.fail("参数错误！");
        }
        Long uid = SecurityUtil.getCurrentUser().getUid();
        List<DiscussSupport> list = discussSupportService.list(Wrappers.lambdaQuery(DiscussSupport.class)
                .eq(DiscussSupport::getDid,did)
                .eq(DiscussSupport::getUid,uid));
        if (list==null || list.size() == 0){  //没有点过赞
            kafkaTemplate.send(AppVariable.DISCUSS_SUPPORT_TOPIC,did+"_"+uid);
            return ResponseEntity.success(true);
        }
        return ResponseEntity.fail("请勿重复点赞！");
    }

    /**
     * 监听 Kafaka 中的点赞事件
     */
    @KafkaListener(topics = {AppVariable.DISCUSS_SUPPORT_TOPIC})
    public void listen(String data, Acknowledgment acknowledgment){
        Long did = Long.parseLong(data.split("_")[0]);
        Long uid = Long.parseLong(data.split("_")[1]);
         //没有点过赞
            // 1. 修改讨论表中的点赞数
            int result= discussService.updateSupportCount(did);
            if (result > 0){
                // 2. 在点赞详情表中添加点赞信息
                DiscussSupport discussSupport = new DiscussSupport();
                discussSupport.setDid(did);
                discussSupport.setUid(uid);
                boolean save =discussSupportService.save(discussSupport);
                if (save){
                    // todo: 手动确认消息已消费
                    acknowledgment.acknowledge();
                }
            }
    }
}
